package com.hb.game.pk.ui.activity.game;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.hb.game.pk.APP;
import com.hb.game.pk.R;
import com.hb.game.pk.adpter.ListViewAdapter;
import com.hb.game.pk.api.Host;
import com.hb.game.pk.api.RedBag;
import com.hb.game.pk.base.BaseActivity;
import com.hb.game.pk.beans.NullBean;
import com.hb.game.pk.beans.RoomList;
import com.hb.game.pk.beans.SLClickRed;
import com.hb.game.pk.event.MoneyChangeEvent;
import com.hb.game.pk.network.RetrofitCreateHelper;
import com.hb.game.pk.ui.activity.game.red.OpenRedActivity;
import com.hb.game.pk.ui.activity.game.red.SendRedActivity;
import com.hb.game.pk.utils.DialogUtils;
import com.hb.game.pk.utils.LogUtils;
import com.hb.game.pk.utils.SocketUtils;
import com.hb.game.pk.utils.SoftKeyboardFixerForFullscreen;
import com.hb.game.pk.utils.StringUtils;
import com.hb.game.pk.utils.ToastUtils;
import com.hb.game.pk.widgets.titlebar.TitleBar;

import org.greenrobot.eventbus.EventBus;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SaoLeiChatActivity1 extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    MaterialDialog redDialog;
    MaterialDialog moneyDialog;
    RoomList.DataBean dataBean;
    List<Map> data;
    Call<Map> redCall;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.rv_list)
    ListView rv_list;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    private int clickPosition = -1;
    Call<SLClickRed> clickCall;
    SocketUtils socketUtils;
    WebSocketClient open;
    String clickHbId = "0";
    SLClickRed.DataBean clickData;
    Call<NullBean> openResult;
    ListViewAdapter myAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chat;
    }

    @Override
    protected int getRootViewId() {
        return R.id.layout_root;
    }

    @Override
    protected int getRefreshId() {
        return 0;
    }

    @Override
    protected int getListViewId() {
        return 0;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        SoftKeyboardFixerForFullscreen.assistActivity(this);
        Intent intent = getIntent();
        String room = intent.getStringExtra("room");
        dataBean = new Gson().fromJson(room, RoomList.DataBean.class);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        titleBar.getLlLeft().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SaoLeiChatActivity1.this.finish();
            }
        });
        titleBar.setTitle(dataBean.getTitle());
    }

    @Override
    protected void onRefreshData() {
        super.onRefreshData();
        redCall = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).inRoom(dataBean.getRoom_id());
        redCall.enqueue(new Callback<Map>() {
            @Override
            public void onResponse(Call<Map> call, Response<Map> response) {
                Map body = response.body();
                if (body == null) {
                    ToastUtils.showToast("请求错误");
                    return;
                }
                if (Float.parseFloat(body.get("status").toString()) != 1.0f) {
                    ToastUtils.showToast(body.get("info").toString());
                    return;
                }
                if (body.get("data") != null) {
                    data = (List<Map>) body.get("data");
//                    initAdapter();
                    initMyAdapter();
                    Map<String, String> jsonMap = new HashMap<>();
                    jsonMap.put("roomid", dataBean.getRoom_id());
                    jsonMap.put("uid", APP.uid);
                    jsonMap.put("m", "index");
                    jsonMap.put("a", "slogin");
                    String socketJson = new Gson().toJson(jsonMap);
                    try {
                        doConn(socketJson);
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                        ToastUtils.showToast("socket错误");
                    }
                }
            }

            @Override
            public void onFailure(Call<Map> call, Throwable t) {
                ToastUtils.showToast("网络请求错误");
            }
        });

        Call<NullBean> getpeople = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).getpeople();
        getpeople.enqueue(new Callback<NullBean>() {
            @Override
            public void onResponse(Call<NullBean> call, Response<NullBean> response) {
                NullBean body = response.body();
                if (body == null) {
                    ToastUtils.showToast("请求错误");
                    return;
                }
                if (body.getStatus() != 1) {
                    ToastUtils.showToast(body.getInfo());
                    return;
                }
                if (body.getData() != null)
                    titleBar.setRightText(body.getData().toString());
            }

            @Override
            public void onFailure(Call<NullBean> call, Throwable t) {
                ToastUtils.showToast("网络请求错误");
            }
        });
    }

    protected void initMyAdapter() {
        if (myAdapter == null) {
            myAdapter = new ListViewAdapter(this, rv_list);
            myAdapter.setType(1);
            myAdapter.setNewData(data);
            rv_list.setAdapter(myAdapter);
            rv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                    clickPosition = position;
                    List<Map> data = myAdapter.getData();
                    Map map = myAdapter.getData().get(position);
                    if (map.containsKey("m")) {
                        String m = map.get("m").toString();
                        if ("2.0".equals(m) || "3.0".equals(m)) {
                            return;
                        }
                        Map<String, Object> mapData = (Map<String, Object>) map.get("data");
                        clickHbId = mapData.get("hongbao_id").toString().replace(".0", "");
                    } else {
                        clickHbId = map.get("id").toString().replace(".0", "");
                    }
                    rv_list.post(new Runnable() {
                        @Override
                        public void run() {
                            myAdapter.setStatus(position);
                        }
                    });
                    showClickBagDialog(myAdapter, position);
                }
            });
            if (data != null)
                rv_list.setSelection(myAdapter.getData().size() - 1);
        } else {
            myAdapter.setNewData(data);
            if (data != null)
                rv_list.setSelection(myAdapter.getData().size() - 1);
        }
    }

    Dialog dialog;

    private void showClickBagDialog(final ListViewAdapter myAdapter, final int position) {
        clickCall = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).slClickRedBag(clickHbId);
        clickCall.enqueue(new Callback<SLClickRed>() {
            @Override
            public void onResponse(Call<SLClickRed> call, Response<SLClickRed> response) {
                SLClickRed body = response.body();
                if (body == null) {
                    ToastUtils.showToast("请求错误");
                    return;
                }
                if (body.getStatus() != 1) {
                    ToastUtils.showToast(body.getInfo());
                    return;
                }
                clickData = body.getData();
                View inflate = View.inflate(SaoLeiChatActivity1.this, R.layout.dialog_red_open, null);
                ImageView ivOpen = (ImageView) inflate.findViewById(R.id.iv_open);
                TextView tvTs = (TextView) inflate.findViewById(R.id.tv_ts);
                TextView tvDetail = (TextView) inflate.findViewById(R.id.tv_detail);
                ImageView ivClose = (ImageView) inflate.findViewById(R.id.iv_close);
                TextView tvName = (TextView) inflate.findViewById(R.id.tv_name);
                if (redDialog == null) {
                    if (clickData.getType() != 1) {
                        tvDetail.setVisibility(View.VISIBLE);
                        tvTs.setVisibility(View.VISIBLE);
                        tvTs.setText(clickData.getRemark());
                        ivOpen.setVisibility(View.GONE);
                    } else {
                        ivOpen.setVisibility(View.VISIBLE);
                        tvDetail.setVisibility(View.GONE);
                        tvTs.setVisibility(View.GONE);
                    }
                    if (clickData.getUser_id().equals(APP.uid)) {
                        tvDetail.setVisibility(View.VISIBLE);
                    }
                    tvDetail.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.putExtra("clickHbId", clickHbId);
                            dialog.dismiss();
                            startActivity(OpenRedActivity.class, intent);
                        }
                    });
                    ivOpen.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            openResult = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).openRed(clickData.getId());
                            openResult.enqueue(new Callback<NullBean>() {
                                @Override
                                public void onResponse(Call<NullBean> call, Response<NullBean> response) {
                                    NullBean body = response.body();
                                    if (body == null) {
                                        ToastUtils.showToast("请求错误");
                                        return;
                                    }
                                    if (body.getStatus() != 1) {
                                        ToastUtils.showToast(body.getInfo());
                                        return;
                                    }
                                    Intent intent = new Intent();
                                    intent.putExtra("clickHbId", clickHbId);
                                    dialog.dismiss();
                                    startActivity(OpenRedActivity.class, intent);
                                }

                                @Override
                                public void onFailure(Call<NullBean> call, Throwable t) {
                                    ToastUtils.showToast("网络请求错误");
                                }
                            });
                        }
                    });
                    dialog = DialogUtils.showHongBaoDialog(SaoLeiChatActivity1.this, inflate);
                    ivClose.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                } else {
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    } else {
                        if (clickData.getType() != 1) {
                            tvDetail.setVisibility(View.VISIBLE);
                            tvTs.setVisibility(View.VISIBLE);
                            tvTs.setText(clickData.getRemark());
                            ivOpen.setVisibility(View.GONE);
                        } else {
                            ivOpen.setVisibility(View.VISIBLE);
                            tvDetail.setVisibility(View.GONE);
                            tvTs.setVisibility(View.GONE);
                        }
                        if (clickData.getUser_id().equals(APP.uid)) {
                            tvDetail.setVisibility(View.VISIBLE);
                        }
                        dialog.show();
                    }
                }


                tvName.setText(clickData.getUsername());
//                String trim = StringUtils.getString(avatar);
//                int res = 0;
//                if (StringUtils.isEmpty(trim)) {
//                    res = R.mipmap.ic_head_normal;
//                } else {
//                    int i = Integer.parseInt(trim);
//                    res = APP.headResource.get(i - 1);
//                }
//                ivHead.setBackgroundResource(res);
                if (clickData.getType() == 1) {
                    // 领取
                    ivOpen.setVisibility(View.VISIBLE);
                } else if (clickData.getType() == 2) {
                    // 过期
                    tvTs.setText(clickData.getRemark());
                    tvTs.setVisibility(View.VISIBLE);
                } else {
                    // 领完
                    tvTs.setText(clickData.getRemark());
                    tvTs.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onFailure(Call<SLClickRed> call, Throwable t) {
                ToastUtils.showToast("网络请求错误");
            }
        });
    }

    Map map;

    private void doConn(final String text) throws URISyntaxException {
        if (socketUtils == null) {
            socketUtils = new SocketUtils(Host.SOCKETHOST, text);
            socketUtils.setOnOpenListener(new SocketUtils.OnOpenListener() {
                @Override
                public void setOnOpenListener(ServerHandshake handshakedata) {
                    socketUtils.setText(text);
                }
            });
            socketUtils.setOnCloseListener(new SocketUtils.OnCloseListener() {
                @Override
                public void setOnCloseListener(int code, String reason, boolean remote) {
                }
            });
            socketUtils.setOnErrorListener(new SocketUtils.OnErrorListener() {
                @Override
                public void setOnErrorListener(Exception ex) {
                    LogUtils.d("OnErrorListener");
                    ex.printStackTrace();
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            if (open != null) {
                                open.reconnect();
                            }
                        }
                    }.start();
                }
            });
            socketUtils.setOnMessageListener(new SocketUtils.OnMessageListener() {
                @Override
                public void setOnMessageListener(String message) {
                    if (message.contains("logout"))
                        return;
                    if (message.contains("slogin"))
                        return;
                    LogUtils.d("message___  " + message);
                    if (myAdapter != null) {
                        map = new Gson().fromJson(message, Map.class);
                        if (!dataBean.getRoom_id().equals(map.get("roomid").toString())) return;
                        rv_list.post(new Runnable() {
                            @Override
                            public void run() {
                                myAdapter.addMore(map);
//                                rv_list.setSelection(myAdapter.getData().size() - 1);
                            }
                        });
                    }
                }
            });
        }
        if (open == null) {
            open = socketUtils.open();
        }
        open.connect();

    }

    @Override
    public boolean isNeedLoadMore() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (redCall != null) {
            redCall.cancel();
        }
        if (open != null) {
            open.close();
        }
        EventBus.getDefault().post(new MoneyChangeEvent());
    }

    @OnClick({R.id.tv_start, R.id.tv_money})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_start:
                Intent intent = new Intent();
                intent.putExtra("room_id", dataBean.getRoom_id());
                startActivity(SendRedActivity.class, intent);
                break;
            case R.id.tv_money:
                Call<NullBean> getmoney = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).getmoney();
                getmoney.enqueue(new Callback<NullBean>() {
                    @Override
                    public void onResponse(Call<NullBean> call, Response<NullBean> response) {
                        NullBean body = response.body();
                        if (body == null) {
                            ToastUtils.showToast("请求错误");
                            return;
                        }
                        if (body.getStatus() != 1) {
                            ToastUtils.showToast(body.getInfo());
                            return;
                        }
                        if (moneyDialog == null) {
                            View inflate = View.inflate(SaoLeiChatActivity1.this, R.layout.dialog_money_view, null);
                            Button btnClose = (Button) inflate.findViewById(R.id.btn_close);
                            TextView tvMoney = (TextView) inflate.findViewById(R.id.tv_money);
                            if (!StringUtils.isEmpty(body.getData().toString())) {
                                tvMoney.setText(String.format(getResources().getString(R.string.mine_money), (Float.parseFloat(body.getData().toString()) / 100f) + ""));
                            } else {
                                tvMoney.setText("0");
                            }
                            moneyDialog = new MaterialDialog.Builder(SaoLeiChatActivity1.this)
                                    .customView(inflate, false).show();
                            btnClose.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (moneyDialog != null && moneyDialog.isShowing()) {
                                        moneyDialog.dismiss();
                                    }
                                }
                            });
                        } else {
                            if (moneyDialog.isShowing()) {
                                moneyDialog.dismiss();
                            } else {
                                View customView = moneyDialog.getCustomView();
                                TextView tvMoney = (TextView) customView.findViewById(R.id.tv_money);
                                if (!StringUtils.isEmpty(body.getData().toString())) {
                                    tvMoney.setText(String.format(getResources().getString(R.string.mine_money), (Float.parseFloat(body.getData().toString()) / 100f) + ""));
                                } else {
                                    tvMoney.setText("0");
                                }
                                moneyDialog.show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<NullBean> call, Throwable t) {
                        ToastUtils.showToast("网络请求错误");
                    }
                });
                break;
        }
    }
}
